<?php
/**
 * Created by PhpStorm.
 * User: 舒中荣
 * Date: 2018/8/28
 * Time: 16:19
 */

namespace App\Http\Controllers\Common;


use App\Models\ImgCode;
use Gregwar\Captcha\CaptchaBuilder;
use Illuminate\Http\Request;

class CaptchaController extends ApiController
{
    /**
     * 验证码生成
     * GET：/api/public/getImgCode
     * @param string device 设备号
     * @return  mixed JSON { code: 错误码, message: 错误信息}
     * */
    public function getImgCode(Request $request)
    {
        $input['device'] = $request->get('device', '');
        if (empty($input['device'])) {
            return $this->setStatusCode(412)->message('缺少设备号！');
        }
        $builder = new CaptchaBuilder();
        $builder->build();
//        $builder->setBackgroundColor(8,160,207);
//        $builder->setTextColor(248,248,255);
        $imgCode = $builder->inline();  //获取图形验证码的url
//        $request->session()->put('piccode', $builder->getPhrase());  //将图形验证码的值写入到session中
        $input['code'] = strtolower($builder->getPhrase());
        $time = time() - (3600 * 24);
        ImgCode::where([['created_at', '<', date('Y-m-d H:i:s', $time)]])->delete();
        $re = ImgCode::insert($input);
        if ($re === false) {
            return $this->setStatusCode(412)->message('生成验证码失败！');

        }
        return $this->success(['img_code' => $imgCode]);
    }

    /**
     * 功能：验证码验证
     * @param string device 设备号
     * @param string check_code 验证码
     * @return mixed JSON { code: 错误码, message: 错误信息}
     */
    public function checkCode(Request $request)
    {
        $input['device'] = $request->get('device', '');
        $input['code'] = $request->get('check_code', '');
        if (empty($input['device'])) {
            return $this->setStatusCode(412)->message('缺少设备号！');
        }
        if (empty($input['code'])) {
            return $this->setStatusCode(412)->message('缺少图形验证码！');
        }
        $re = self::checkGraphicCode($input);
        if ($re['code'] > 0) {
            return $this->setStatusCode(412)->message('您输入的验证码错误！');
        }
        return $this->message('您输入验证码正确！');
    }

    /**
     * 功能：验证码验证
     * @param array $input 设备号
     * @return array
     */
    public static function checkGraphicCode($input)
    {
        $input['code'] = strtolower($input['code']);
        if (ImgCode::where([['device', $input['device']], ['time', '>', 0]])->orderBy('created_at', 'desc')->value('code') != $input['code']) {
            return ['code' => 1, 'msg' => '您输入的验证码错误或已失效！'];
        } else {
            ImgCode::where([['device', $input['device']], ['code', $input['code']]])->decrement('time');
            return ['code' => 0, 'msg' => '您输入验证码正确！'];
        }
    }

}